package com.slipper.system.scheduled;

import java.io.IOException;
import java.util.Properties;

import javax.sql.DataSource;

import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

public class ScheduledConfiguration {
    @Bean
    public JobFactory jobFactory(ApplicationContext applicationContext) {
        ScheduledBeanJobFactory jobFactory = new ScheduledBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return jobFactory;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory, DataSource dataSource) throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        // 用于quartz集群,QuartzScheduler
        // 启动时更新己存在的Job，这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
        factory.setOverwriteExistingJobs(true);
        // 用于quartz集群,加载quartz数据源
        factory.setDataSource(dataSource);
        factory.setJobFactory(jobFactory);
        // QuartzScheduler 延时启动，应用启动完5秒后 QuartzScheduler 再启动
        factory.setStartupDelay(5);
        // 用于quartz集群,加载quartz数据源配置
        factory.setQuartzProperties(quartzProperties());

        return factory;
    }
    
    @Bean
    public ScheduledListener scheduledListener() {
        return new ScheduledListener();
    }
    
    /**
     * 加载quartz数据源配置, quartz集群时用到
     */
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }
}
